#Region " Imports "

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports BlazeApps.Library.Resources
Imports BlazeApps.Library.Nodes
Imports BlazeApps.Library.TreeViews
Imports System.Web.UI

#End Region

Partial Class Usercontrols_Resourcegallery
    Inherits UserControlBase

#Region " Enums, Memebers and Properties "

    Private DataPageLocal As New PagedDataSource

    Public Property sortCriteria() As String
        Get
            Return CStr(ViewState("sortCriteria"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortCriteria") = Value
        End Set
    End Property

    Public Property sortDir() As String
        Get
            Return CStr(ViewState("sortDir"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortDir") = Value
        End Set
    End Property

    Protected Property NodeGuid() As Guid
        Get
            Return GetGuidFromVS("NodeID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("NodeID", value)
        End Set
    End Property

    Protected Property ResourceGuid() As Guid
        Get
            Return GetGuidFromVS("ResourceID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("ResourceID", value)
        End Set
    End Property

    Protected Property Update() As Boolean
        Get
            Return GetBooleanFromVS("Update")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("Update", value)
        End Set
	End Property

	Public Property ItemGuid() As Guid
		Get
			Return GetGuidFromVS("ItemGuid")
		End Get
		Set(ByVal value As Guid)
			ViewState.Add("ItemGuid", value)
		End Set
	End Property

	Public Property HideFileSelection() As Boolean
		Get
			Return GetBooleanFromVS("HideFileSelection")
		End Get
		Set(ByVal value As Boolean)
			ViewState.Add("HideFileSelection", value)
		End Set
	End Property

	Public Property IsLoadedAsOption() As Boolean
		Get
			Return GetBooleanFromVS("IsLoadedAsOption")
		End Get
		Set(ByVal value As Boolean)
			ViewState.Add("IsLoadedAsOption", value)
		End Set
	End Property

	Public Property GalleryType() As TreeViewNodes.TreeType
		Get
			Return CType(ViewState("GalleryType"), TreeViewNodes.TreeType)
		End Get
		Set(ByVal value As TreeViewNodes.TreeType)
			ViewState.Add("GalleryType", value)
		End Set
	End Property

#End Region

#Region " Page Events "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.MessageLabel = Me.uxMessagesLabel
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ScriptManager.GetCurrent(Page).RegisterPostBackControl(uxUploadFileButton)

		If GalleryType = TreeViewNodes.TreeType.ResourceTree Then
			SetPageTitle(Resources.Resource.ResourceGallery)
			Me.uxPrivateCheckBox.Enabled = False
		ElseIf GalleryType = TreeViewNodes.TreeType.UserTree Then
			If Not IsLoadedAsOption Then
				SetPageTitle(Resources.Resource.MyGallery)
			End If
		End If

		If IsUserAuthenticated And (EnableUserGalleries OrElse IsGalleryModerator() OrElse (GalleryType = TreeViewNodes.TreeType.ResourceTree)) Then

			If GalleryType = TreeViewNodes.TreeType.UserTree Then
				GetQueryStringValues()
			End If

			If Me.Page.IsPostBack = False Then

				'Set Default Sort Order and Direction
				Me.sortCriteria = "resourcename"
				Me.sortDir = "asc"

				PopulateRootLevel(Me.uxResourceGalleryTreeView, GalleryType, CurrentUserID)
				LoadPage()

				Me.uxCharCountLabel.Text = "250"
				Me.uxFileDescriptionTextBox.Attributes.Add("maxCharacters", "250")
				Me.uxFileDescriptionTextBox.Attributes.Add("onkeyup", "return CharacterCount(this, " & Me.uxCharCountLabel.ClientID & ");")

			End If

			ConfigBaseNavCtrls()

			Me.uxMemberPanel.Visible = ShowControls(SecurityMask.Member, True)

			uxResourceCollapsiblePanelExtender.CollapsedImage = String.Format("~/App_Themes/{0}/images/icons/collapse.gif", Page.Theme.ToString.Trim)
			uxResourceCollapsiblePanelExtender.ExpandedImage = String.Format("~/App_Themes/{0}/images/icons/expand.gif", Page.Theme.ToString.Trim)
		Else
			uxMemberPanel.Visible = False
			uxMessagesLabel.Text = Resources.Resource.AdminDisabledGalleries.ToString
		End If

		'Me.uxMemberPanel.Visible = ShowControls(SecurityMask.Editor, True)

    End Sub

#End Region

#Region " Save Data "

    Private Sub AddFolder(ByVal FolderName As String)
        Dim NodeItem As ResourceTreeNodeDetail = ResourceTreeNodeDetail.NewResourceTreeNodeDetail()

        If Not (Me.uxResourceGalleryTreeView.SelectedNode Is Nothing) Then
            NodeItem.parentnodeid = ConvertToGuid(Me.uxResourceGalleryTreeView)
        End If

        NodeItem.name = FolderName
        NodeItem.Save()

        LoadTree()
    End Sub

#End Region

#Region " Load Data "

    Private Sub LoadPage()
        LoadPageSize(Me.uxPageSizeDropDownList)
    End Sub

    Private Sub LoadTree()
        Me.uxResourceGalleryTreeView.Nodes.Clear()
		PopulateRootLevel(Me.uxResourceGalleryTreeView, GalleryType, CurrentUserID)
        Me.uxResourceGalleryTreeView.ExpandAll()
    End Sub

    Public Overloads Overrides Sub BindDataItems()
        Dim List As New ResourceList
        Dim DS As New DataSet
        Dim DT As New DataTable
        Dim DV As New DataView

        DS = List.GetResourceListByNode(NodeGuid)

        Me.RecordCount = DS.Tables(0).Rows.Count

        DT = DS.Tables(0)

        DV.Table = DT

        DV.Sort = Me.sortCriteria & " " & Me.sortDir

        Me.DataPage.DataSource = DV
        Me.DataPage.AllowPaging = True
        Me.DataPage.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.DataPage.CurrentPageIndex = Me.PageNumber

        CreatePagingLinks()

		With Me.uxGalleryDataList
			.DataSource = Me.DataPage
			.DataBind()
		End With

    End Sub

#End Region

#Region " Form Controls Events "

	Protected Sub uxTreeView_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxResourceGalleryTreeView.SelectedNodeChanged
		ViewState.Add("SelectedNode", Me.uxResourceGalleryTreeView.SelectedValue.ToString.Trim)
		NodeGuid = ConvertToGuid(Me.uxResourceGalleryTreeView)

		Me.uxUploadFileButton.Enabled = True
		Me.uxInfoLabel.Visible = False

		Me.PageNumber = 0
		BindDataItems()

		uxResourceGalleryTreeView.SelectedNode.ImageUrl = String.Format("~/App_Themes/{0}/images/icons/folderopened.gif", Page.Theme)

		ResetNodeFolder(Me.uxResourceGalleryTreeView.SelectedValue.ToString().Trim())

	End Sub

	Protected Sub uxTreeView_TreeNodePopulate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles uxResourceGalleryTreeView.TreeNodePopulate
		PopulateSubLevel(e.Node.Value.Trim, e.Node, GalleryType, CurrentUserID)
	End Sub

	Protected Sub uxUploadFileButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxUploadFileButton.Click

		Dim ResourceID As Guid = Guid.Empty

		If GalleryType = TreeViewNodes.TreeType.ResourceTree Then

			If Update Then
				ResourceID = UpdateResource(Me.uxSelectFileUpload, Me.uxThumbNailFileupload, Me.uxUploadTitleTextBox.Text.Trim, Me.uxFileDescriptionTextBox.Text.Trim, ResourceGuid, UploadType.UpdateItem, False)
			Else
				ResourceID = InsertResource(Me.uxSelectFileUpload, Me.uxThumbNailFileupload, Me.uxUploadTitleTextBox.Text.Trim, Me.uxFileDescriptionTextBox.Text.Trim, ConvertToGuid(Me.uxResourceGalleryTreeView), UploadType.NewItem, False)
			End If

		ElseIf GalleryType = TreeViewNodes.TreeType.UserTree Then

			If Me.uxSelectFileUpload.PostedFile.ContentType.IndexOf("image/") = 0 Or _
			 Me.uxSelectFileUpload.PostedFile.ContentType.IndexOf("video/") = 0 Or _
			 System.IO.Path.GetExtension(Me.uxSelectFileUpload.PostedFile.FileName.ToString).ToUpper() = ".FLV" = True Or _
			 System.IO.Path.GetExtension(Me.uxSelectFileUpload.PostedFile.FileName.ToString).ToUpper() = ".SWF" = True Or _
			 System.IO.Path.GetExtension(Me.uxSelectFileUpload.PostedFile.FileName.ToString).ToUpper() = ".ZIP" = True Then

				If Update Then
					ResourceID = UpdateResource(Me.uxSelectFileUpload, Me.uxThumbNailFileupload, Me.uxUploadTitleTextBox.Text.Trim, Me.uxFileDescriptionTextBox.Text.Trim, ResourceGuid, UploadType.NewItem, Me.uxPrivateCheckBox.Checked)
				Else
					ResourceID = InsertResource(Me.uxSelectFileUpload, Me.uxThumbNailFileupload, Me.uxUploadTitleTextBox.Text.Trim, Me.uxFileDescriptionTextBox.Text.Trim, ConvertToGuid(Me.uxResourceGalleryTreeView), UploadType.UpdateItem, Me.uxPrivateCheckBox.Checked)
				End If

				uxOptions.ItemGuid = ResourceID
				uxOptions.SetInitialOptions = True
				uxOptions.SaveOptions()
				uxOptions.LoadOptions()

			Else
				ScriptManager.RegisterStartupScript(uxUploadFileButton, Me.GetType(), "warning", String.Format("window.alert('{0}');", Resources.Resource.OnlyFileTypes), True)
			End If

		End If

		BindDataItems()

	End Sub

	Protected Sub AttachSelection(ByVal sender As Object, ByVal e As CommandEventArgs)
		Dim Item As ItemResource = ItemResource.NewItemResource()
		Item.Itemid = ItemGuid
		Item.ResourceID = New Guid(e.CommandArgument.ToString)
		Item.Save()
	End Sub

	Protected Sub uxAddFolderImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxAddFolderImageButton.Click

		AddFolder(Me.uxNodeNameTextBox.Text.Trim)

	End Sub

	Protected Sub uxDeleteFolderImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxDeleteFolderImageButton.Click
		ResourceTreeNodeDetail.DeleteResourceTreeNodeDetail(ConvertToGuid(Me.uxResourceGalleryTreeView))

		LoadTree()
	End Sub

	Protected Sub uxUpdateFolderImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxUpdateFolderImageButton.Click

		Dim NodeItem As ResourceTreeNodeDetail = ResourceTreeNodeDetail.GetResourceTreeNodeDetail(ConvertToGuid(Me.uxResourceGalleryTreeView))

		NodeItem.nodeid = ConvertToGuid(Me.uxResourceGalleryTreeView)
		NodeItem.name = Me.uxNodeNameTextBox.Text.Trim
		NodeItem.Save()

		LoadTree()

	End Sub

	Protected Sub SecureItem(ByVal sender As Object, ByVal e As CommandEventArgs)
		Dim Item As String() = Split(e.CommandArgument.ToString, "|")

		Me.uxSecurityModalPopupExtender.Show()

		uxSecurity.ItemGuid = ConvertToGuid(Item(0).ToString.Trim)
		uxSecurity.ItemName = Item(1).ToString.Trim
		uxSecurity.BindDataItems()
		uxSecurity.LoadItemName()

	End Sub

	Protected Sub ItemOptions(ByVal sender As Object, ByVal e As CommandEventArgs)

		Me.uxOptionsModalPopupExtender.Show()

		uxOptions.ItemGuid = ConvertToGuid(e.CommandArgument.ToString)
		uxOptions.LoadOptions()

	End Sub

	Protected Sub EditResource(ByVal sender As Object, ByVal e As CommandEventArgs)
		Dim Item As ResourceDetail = ResourceDetail.GetResourceDetail(ConvertToGuid(e.CommandArgument.ToString))

		Me.uxFileDescriptionTextBox.Text = Item.resourcedesc
		Me.uxUploadTitleTextBox.Text = Item.resourcetitle

		ResourceGuid = ConvertToGuid(e.CommandArgument.ToString)
		Update = True

	End Sub

	Protected Sub DeleteItem(ByVal sender As Object, ByVal e As CommandEventArgs)

		ResourceDetail.DeleteResourceDetail(ConvertToGuid(e.CommandArgument.ToString))
		BindDataItems()

	End Sub

#End Region

#Region " Helpers and Methods "

	Private Sub GetQueryStringValues()
		ItemGuid = GetGuidFromQueryString("id")

		If ItemGuid = Guid.Empty Then
			ItemGuid = GetGuidFromQueryString("postid")
		End If

	End Sub

	Private Sub ConfigBaseNavCtrls()

		Me.PagingTopPanel = Me.uxPagingTopPanel
		Me.PagingBottomPanel = Me.uxPagingBottomPanel

		Me.RepeaterTop = Me.uxPagesTopRepeater
		Me.RepeaterBottom = Me.uxPagesBottomRepeater

		Me.NextTopLinkButton = Me.uxTopNextLinkButton
		Me.PreviousTopLinkButton = Me.uxTopPrevLinkButton
		Me.NextBottomLinkButton = Me.uxBottomNextLinkButton
		Me.PreviousBottomLinkButton = Me.uxBottomPrevLinkButton

		Me.DataPage = DataPageLocal
		Me.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
		Me.PagesToDisplay = 10

		Me.ItemsPerPageDropDown = Me.uxPageSizeDropDownList
		Me.ItemsPerPageLabel = Me.uxItemsPerPageLabel
		Me.PagerInfoLabel = Me.uxPagerInfoLabel

		AddHandler Me.RepeaterTop.ItemCommand, AddressOf PagingRepeater_ItemCommand
		AddHandler Me.RepeaterBottom.ItemCommand, AddressOf PagingRepeater_ItemCommand

	End Sub

	Protected Sub SaveSelection(ByVal sender As Object, ByVal e As CommandEventArgs)

		Dim Item As String() = Split(e.CommandArgument.ToString, "|")

		Dim AttachmentList As New StringBuilder

		Dim AttachmentLink As String = Item(0).ToString().Trim()
		Dim AttachmentThumb As String = Item(1).ToString().Trim()
		Dim ContentType As String = Item(2).ToString().Trim()
		Dim AttachmentName As String = Item(3).ToString().Trim()

		AttachmentList.Append(vbCrLf)

		If InStr(ContentType, "image/") Then
			AttachmentList.Append(String.Format("opener.document.getElementById('txtUrl').value = ""<a href='{0}{1}' target='_blank' runat='server'><IMG src='{0}{2}' border='0' runat='server'></a><br>"";", AppPath, Replace(AttachmentLink, "~/", ""), Replace(AttachmentThumb, "~/", "")))
		ElseIf InStr(ContentType, "video/") Then
			AttachmentList.Append(String.Format("opener.document.getElementById('txtUrl').value = ""<a href='{0}{1}' target='_blank' runat='server'><IMG src='{0}{2}' border='0' runat='server'></a><br>"";", AppPath, Replace(AttachmentLink, "~/", ""), Replace(AttachmentThumb, "~/", "")))
		Else
			AttachmentList.Append(String.Format("opener.document.getElementById('txtUrl').value = ""<a href='{0}{1}' target='_blank' runat='server'>{2}</a><br>"";", AppPath, Replace(AttachmentLink, "~/", ""), AttachmentName))
		End If

		AttachmentList.Append(vbCrLf)

		AttachmentList.Append("window.close();")
		AttachmentList.Append(vbCrLf)

		AttachmentList.Append(vbCrLf)

		ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "SendLinkValues", AttachmentList.ToString, True)
	End Sub

	Private Sub ResetNodeFolder(ByVal searchValue As String)
		For Each tn As TreeNode In uxResourceGalleryTreeView.Nodes
			If tn.ChildNodes.Count > 0 Then
				For Each cTn As TreeNode In tn.ChildNodes
					ResetChildNodeFolder(cTn, searchValue)
				Next
			End If
		Next
	End Sub

	Private Sub ResetChildNodeFolder(ByVal tn As TreeNode, ByVal searchValue As String)
		If Not tn.Value = searchValue Then
			tn.ImageUrl = String.Format("~/App_Themes/{0}/images/icons/folder.gif", Page.Theme)
			Exit Sub
		End If

		If tn.ChildNodes.Count > 0 Then
			For Each tnC As TreeNode In tn.ChildNodes
				ResetChildNodeFolder(tnC, searchValue)
			Next
		End If
	End Sub

#End Region

End Class
